package repository

import (
	"sync"
	"github.com/zhulizhe/golang-shortlink/internal/model"
)

type LinkRepository interface {
	Save(link *model.Link) error
	Get(shortKey string) (*model.Link, bool)
	IncrVisit(shortKey string)
}

type MemoryLinkRepository struct {
	data map[string]*model.Link
	mu   sync.RWMutex
}

func NewMemoryLinkRepository() *MemoryLinkRepository {
	return &MemoryLinkRepository{
		data: make(map[string]*model.Link),
	}
}

func (r *MemoryLinkRepository) Save(link *model.Link) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.data[link.ShortKey] = link
	return nil
}

func (r *MemoryLinkRepository) Get(shortKey string) (*model.Link, bool) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	link, ok := r.data[shortKey]
	return link, ok
}

func (r *MemoryLinkRepository) IncrVisit(shortKey string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	if link, ok := r.data[shortKey]; ok {
		link.VisitCount++
	}
}
